package com.atguigu.gmall.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.atguigu.gmall.user.client.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @Author: lx
 * @Time: 9:26
 * @Description:
 */
@RestController
@RequestMapping("/api/order")
public class OrderApiController {

    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;
    //去结算页面  回显  收货地址 清单  小计   /**/auth/**  必须登录
    @GetMapping("/auth/trade")
    public Map<String,Object> trade(HttpServletRequest request){
        Map<String,Object> result = new HashMap<>();
        //1、收货地址集合
        List<UserAddress> userAddressList = userFeignClient.findUserAddress();
        result.put("userAddressList",userAddressList);
        //2:商品清单
        List<CartInfo> cartListByChecked = cartFeignClient.findCartListByChecked();
        //订单详情集合
        List<OrderDetail> orderDetailList = cartListByChecked.stream().map(cartInfo -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderPrice(cartInfo.getSkuPrice());//实时价格
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            orderDetail.setSkuNum(cartInfo.getSkuNum());//数量
            orderDetail.setSkuId(cartInfo.getSkuId());
            orderDetail.setSkuName(cartInfo.getSkuName());
            return orderDetail;
        }).collect(Collectors.toList());
        result.put("detailArrayList",orderDetailList);
        //3:小计
        //总件数
        long totalNum = orderDetailList.stream().collect(
                Collectors.summarizingInt(OrderDetail::getSkuNum)).getSum();
        System.out.println("商品总件数："  + totalNum);
        result.put("totalNum",totalNum);
        //商品总金额
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderDetail orderDetail : orderDetailList) {
            totalAmount = totalAmount.add(orderDetail.getOrderPrice().
                    multiply(new BigDecimal(orderDetail.getSkuNum())));
        }
        result.put("totalAmount",totalAmount);
        //订单号或交易号
        // 1： UUID  2：雪花算法  保存Redis中  获取Redis取校验  删除
        // 3:  值 MD5   userId + skuId   MD5(371)  交易号 生成方式
        // 4:  userId+ 时间戳 + skuId
        // 防止二次提交
        String tradeNo = UUID.randomUUID().toString();
        String userId = AuthContextHolder.getUserId(request);
        redisTemplate.opsForValue().set(RedisConst.USER_TRADENO + userId,tradeNo);
        result.put("tradeNo",tradeNo);

        return result;
    }

    //提交订单
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(String tradeNo, @RequestBody OrderInfo orderInfo
      ,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        //1:检查是否二次提交   判断交易号是否正确或是是否存在
        System.out.println("交易号：" + tradeNo);
        Object o = redisTemplate.opsForValue().get(RedisConst.USER_TRADENO + userId);
        if(null != o){
            //有 但是不一样
            if(!o.equals(tradeNo)){
                return Result.fail().message("非法操作");
            }else{
                //有且一样
                redisTemplate.delete(RedisConst.USER_TRADENO + userId);
            }
        }else{
            return Result.fail().message("不要重复提交订单");
        }
        //2:校验商品的库存是否还有货
          // 问仓库系统
        //无货： 购买数量8 大于库存数量 视认为无货    7
        //前端系统  消费系统  后台管理 平台系统  进销存 供货商系统  CMS内容管理系统
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            // 遇到没有货存  直接提示
            Boolean isHasStock = orderInfoService.hasStock(orderDetail.getSkuId(),orderDetail.getSkuNum());
            if(!isHasStock){
                return Result.fail().message(orderDetail.getSkuName() +  ":无货");
            }
        }
        //3：提交订单
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderInfoService.submitOrder(orderInfo);
        return Result.ok(orderId);
    }

    //获取订单对象
    @GetMapping("/auth/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId){
        return orderInfoService.getOrderInfo(orderId);
    }

    @Autowired
    private OrderInfoService orderInfoService;

    //仓库调用我们订单微服务 要求进行折单
    @PostMapping("/orderSplit")
    public String orderSplit(Long orderId,String wareSkuMap){
        //折单
        // wareSkuMap ： [{"wareId":"1","skuIds":["2","10"]},{"wareId":"2","skuIds":["3"]}]
        List<OrderInfo> orderInfoList = orderInfoService.orderSplit(orderId,wareSkuMap);
        //组装返回值
        List<Map> mapList = orderInfoList.stream().map(orderInfo -> {
            return orderInfoService.initWareOrder(orderInfo);
        }).collect(Collectors.toList());
        return JSONObject.toJSONString(mapList);
    }
}
